package com.zt.bus.order.service;

import com.zt.bus.constant.BusConstant;
import com.zt.bus.order.inter.OrderMapper;
import com.zt.bus.order.model.Order;
import com.zt.system.model.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2017/6/30.
 */
@Service
public class OrderStatusCheckService {

    private static int CLOSE_TIME = 10 * 60;// 10分钟后关闭订单
    private static Map<String, Order> userOrderMap = new HashMap<>();

    private static ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(100);

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderService orderService;

    @PostConstruct
    private void init() {
        List<Order> orders = new ArrayList<>();
        orders.addAll(orderMapper.selectByStatus(BusConstant.OrderStatus.TO_BE_PAID));
        orders.addAll(orderMapper.selectByStatus(BusConstant.OrderStatus.PAYMENT_FAILED));
        orders.addAll(orderMapper.selectByStatus(BusConstant.OrderStatus.PAYMENT_CANCEL));

        Long currentTime = new Date().getTime() / 1000;
        for (Order order : orders) {
        	String key = getUserOrderMapKey(order);
            userOrderMap.put(key, order);
            checkAfter(order, (int) Math.max(order.getMakeTime().getTime() / 1000 + CLOSE_TIME - currentTime, 1));
        }
    }

    public void addToCheck(Order order) {
    	String key = getUserOrderMapKey(order);
        for (Map.Entry<String, Order> entry : userOrderMap.entrySet()) {
            String phone = entry.getValue().getBookUserPhone();
            if(order.getBookUserPhone().equals(phone)) {
                throw new BusinessException("请完成未完成的订单！");
            }
        }
//        if (userOrderMap.containsKey(key)) {
//            throw new BusinessException("请完成未完成的订单！");
//        }
        userOrderMap.put(key, order);
        checkAfter(order, CLOSE_TIME);
    }
    
	public String getUserOrderMapKey(Order order) {
		String orderMakeTime = order.getRemark();
		return order.getBookUserPhone() + "-" + orderMakeTime;// 手机号和时间作为键值(同一个手机号可以多次下单)
	}
    
    public void hasPaid(Order order) {
        cancelOrder(order);
    }

    public void cancelOrder(Order order) {
    	String key = getUserOrderMapKey(order);
        Order tmpOrder = userOrderMap.get(key);
        if (tmpOrder != null && tmpOrder.getId().equals(order.getId())) {
            userOrderMap.remove(key);
        }
    }

    private void checkAfter(final Order order, int seconds) {
        scheduledExecutorService.schedule(new TimerTask() {
            @Override
            public void run() {
            	String key = getUserOrderMapKey(order);
            	Order tmpOrder = userOrderMap.get(key);
                if (tmpOrder != null && tmpOrder.getId().equals(order.getId())
                        && (BusConstant.OrderStatus.TO_BE_PAID.equals(order.getStatus())
                        || BusConstant.OrderStatus.PAYMENT_FAILED.equals(order.getStatus())
                        || BusConstant.OrderStatus.PAYMENT_CANCEL.equals(order.getStatus()))) {

                    order.setStatus(BusConstant.OrderStatus.TIMEOUT_OFF);
                    orderService.updatePayStatus(order);
                    userOrderMap.remove(key);
                }
            }
        }, seconds, TimeUnit.SECONDS);
    }
}
